//
//  HWGameDetailController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/3/10.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import JXPagingView

class HWGameDetailController: HWBaseViewController {
    @objc var gameId = ""
    var navMoreButton:UIButton!
    var topView:HWGameDetailTopView!
    var pagingView:JXPagingView!
    var segmentBgView:UIView!
    var segmentedView: JXSegmentedView = JXSegmentedView(frame: CGRect.zero)
    var segmentedDataSource: JXSegmentedTitleDataSource!
    var lineImageView:UIImageView!
    var bottomView:HWGameDetailDownloadView!
    var httpManager = HWGameDetailHttpManager()
    var detailTopModel:HWGameDetailModel = HWGameDetailModel()
    var detailTopGroupModel:HWGameDetailGroupInfoModel = HWGameDetailGroupInfoModel()
    
    let detailVc = HWGameDetailTableController()
    let comment = HWGameDetailCommentController()
    var tagTitles:[String] = []
    var tagModels:[HWGameDetailTagModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        
        initFrame()
        
        loadData()
        
        addAction()
        
    }
}

extension HWGameDetailController {
    private func initUI() -> Void {
        navigationView.titleLabel.text = "游戏详情"
        navigationView.backButton.setImage(UIImage(named: "navBackButton"), for: .normal)
        
        navMoreButton = UIButton(type: .custom)
        navMoreButton.setImage(UIImage(named: "fanxiangdeicotupian"), for: .normal)
        navMoreButton.addTarget(self, action: #selector(navMoreButtonClick(_:)), for: .touchUpInside)
        navigationView.addSubview(navMoreButton)
        
        topView = HWGameDetailTopView()
        topView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 182*widthScale)
        
        segmentBgView = UIView()
        segmentBgView.backgroundColor = .white
        
        segmentedDataSource = JXSegmentedTitleDataSource()
//        segmentedDataSource.titles = ["详情","评价","开服","交易","社区（福利/攻略）"]
        segmentedDataSource.titles = []
        segmentedDataSource.isTitleColorGradientEnabled = true
        segmentedDataSource.titleNormalColor = UIColor.colorWithHexString(hexString: "#333333")
        segmentedDataSource.titleSelectedColor = UIColor.colorWithHexString(hexString: "#F77C2F")
        segmentedDataSource.titleNormalFont = UIFont.systemFont(ofSize: 14*widthScale)
        segmentedDataSource.titleSelectedFont = UIFont.boldSystemFont(ofSize: 18*widthScale)
        segmentedDataSource.isItemSpacingAverageEnabled = true
        
        segmentedView.dataSource = segmentedDataSource
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorHeight = 2*widthScale
        indicator.verticalOffset = 3
        indicator.indicatorColor = .colorWithHexString(hexString: "#F77C2F")
        
        segmentedView.indicators = [indicator]
        segmentedView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 35*widthScale)
        segmentedView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        segmentedView.delegate = self
        segmentBgView.addSubview(self.segmentedView)
        
        lineImageView = UIImageView()
        lineImageView.image = UIImage(named: "gameDetailLine")
        segmentBgView.addSubview(lineImageView)
        
        pagingView = JXPagingView(delegate: self)
        pagingView.automaticallyDisplayListVerticalScrollIndicator = false
        pagingView.mainTableView.backgroundColor = .clear
        pagingView.listContainerView.isCategoryNestPagingEnabled = true
        view.addSubview(pagingView)
        segmentedView.listContainer = pagingView.listContainerView
        
        bottomView = HWGameDetailDownloadView()
        view.addSubview(bottomView)
    }
    
    private func initFrame() -> Void {
        navMoreButton.snp.makeConstraints { make in
            make.centerY.equalTo(navigationView.titleLabel)
            make.right.equalTo(-15*widthScale)
            make.width.equalTo(25*widthScale)
            make.height.equalTo(5*widthScale)
        }
        
        pagingView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        segmentedView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(35*widthScale)
        }
        
        lineImageView.snp.makeConstraints { make in
            make.top.equalTo(segmentedView.snp.bottom).offset(5)
            make.height.equalTo(1*widthScale)
            make.left.right.equalToSuperview()
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
        }
    }
}

extension HWGameDetailController {
    func loadData() -> Void {
        
        let netGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "GameDetail")
        
        netGroup.enter()
        workingQueue.async {
            self.httpManager.getGameDetailTop(gameId: self.gameId) { model in
                self.detailTopModel = model
                self.bottomView.model = self.detailTopModel
//                if HWObjectiveCTools().appCanOpenBundleId(model.ios_bundle) {
//                    self.detailTopModel.haveBundle = true
//                    self.bottomView.model = self.detailTopModel
//                }
                DispatchQueue.global().async{
                    if HWObjectiveCTools().appCanOpenBundleId(model.ios_bundle) {
                        self.detailTopModel.haveBundle = true
                    }
                    DispatchQueue.main.async{
                        self.bottomView.model = self.detailTopModel
                    }
                }
                netGroup.leave()
            } failure: { errorString in
                netGroup.leave()
            }
        }
        
        netGroup.enter()
        workingQueue.async {
            self.httpManager.getGameDetailGroupInfo(gameId: self.gameId) { model in
                self.detailTopGroupModel = model
                netGroup.leave()
            } failure: { errorString in
                netGroup.leave()
            }
        }
        
        netGroup.enter()
        workingQueue.async {
            self.httpManager.getGameDetailTagList(gameId: self.gameId) { models in
                self.tagModels.removeAll()
                self.tagTitles.removeAll()
                for m in models {
                    if m.status == true {
                        self.tagTitles.append(m.name)
                        self.tagModels.append(m)
                    }
                }
                netGroup.leave()
            } failure: { errorString in
                netGroup.leave()
            }

        }
        
        netGroup.notify(queue: workingQueue) {
            DispatchQueue.main.asyncAfter(deadline: .now()) {
                self.detailTopModel.groupInfoModel = self.detailTopGroupModel
                self.topView.model = self.detailTopModel
                self.segmentedDataSource.titles = self.tagTitles
                self.segmentedView.reloadData()
                self.pagingView.reloadData()
            }
            
        }

    }
}

extension HWGameDetailController {
    func addAction() -> Void {
        topView.openServiceButtonClick = {
            self.segmentedView.selectItemAt(index: 2)
        }
        
        topView.joinGroupButtonClick = {
            url in
            if HWLocallyStoredData.getLoginUserID().count > 0 {
                let webVC = XMGWebViewController()
                webVC.url = URL(string: url)
                webVC.isGroup = true
                self.navigationController?.pushViewController(webVC, animated: true)
            } else {
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
        }
        
        topView.giftPackageButtonClick = {
            if HWLocallyStoredData.getLoginUserID().count > 0 {
                let webVC = HWWebViewGameViewController()
                let url = HWGlobalConst.shared.baseUrl + "?ct=app2021&ios=1&ac=lb_list&uid=" + HWLocallyStoredData.getLoginUserID() + "&gid=" + self.gameId + "&member_id=" + HWLocallyStoredData.getCode()
                webVC.urlString = url
                webVC.gname = "领取礼包"
                webVC.panduanStr = "1"
                webVC.gameId = self.gameId
                webVC.isPush = true
                self.navigationController?.pushViewController(webVC, animated: true)
            } else {
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
        }
        
        topView.couponButtonClick = {
            if HWLocallyStoredData.getLoginUserID().count > 0 {
                let webVC = HWWebViewGameViewController()
                let tStr = "\(WMUtil.getTimeSp())\(WMUtil.getRandomNumber(101, to: 998))"
                let sign = "\(HWLocallyStoredData.getLoginUserID())\(tStr)\("fsd213ewdsadqwe2121213edsad")"
                let signMD5 = WMUtil.md5HexDigest(sign) ?? ""
                let url = HWGlobalConst.shared.baseUrl + "?ct=app2021&ac=coupon1&uid=" + HWLocallyStoredData.getLoginUserID() + "&t=" + tStr + "&sign=" + signMD5 + "&gid=" + self.gameId + "&member_id=" + HWLocallyStoredData.getCode()
                webVC.urlString = url
                webVC.gname = "领取优惠券"
                webVC.panduanStr = "2"
                webVC.gameId = self.gameId
                webVC.isPush = true
                self.navigationController?.pushViewController(webVC, animated: true)
            } else {
                let loginController = HWLoginController()
                self.navigationController?.pushViewController(loginController, animated: true)
            }
        }
        
        bottomView.collectionButtonClick = {
            if self.detailTopModel.shoucang == 0{
                self.httpManager.setGameDetailCollection(id: self.gameId,type:"0") { success in
                    self.httpManager.getGameDetailTop(gameId: self.gameId) { model in
                        self.detailTopModel.shoucang = model.shoucang
                        self.detailTopModel.shoucang_id = model.shoucang_id
                        self.bottomView.model = self.detailTopModel
                    } failure: { errorString in
                    }
                } failure: { errorString in
                    self.showHUD(title: errorString)
                }
            }else {
                self.httpManager.setGameDetailCollectionDel(id: self.detailTopModel.shoucang_id,type:"0") { success in
                    self.httpManager.getGameDetailTop(gameId: self.gameId) { model in
                        self.detailTopModel.shoucang = model.shoucang
                        self.detailTopModel.shoucang_id = model.shoucang_id
                        self.bottomView.model = self.detailTopModel
                    } failure: { errorString in
                    }
                } failure: { errorString in
                    self.showHUD(title: errorString)
                }
            }
        }
        
        bottomView.evaluateButtonClick = {
//            let evaluate = HWpingjiajiemianViewController()
//            evaluate.gameIDStr = self.gameId
//            self.navigationController?.pushViewController(evaluate, animated: true)
            let commentRelease = HWGameCommentReleaseController ()
            commentRelease.gameId = self.gameId
            commentRelease.releaseCallBack = {
                self.detailVc.loadData()
                self.comment.loadData()
            }
            self.navigationController?.pushViewController(commentRelease, animated: true)
        }
        
        bottomView.downLoadButtonClick = {

        }
    }
    
    @objc func navMoreButtonClick(_:UIButton) -> Void {
//        let shareView = HWFenXiangGameView()
//        shareView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
//        shareView.delegate = self
//        HWUniversal.getCurrentVc().view.addSubview(shareView)
        
        if HWLocallyStoredData.getLoginUserID().count > 0 {
            if self.detailTopModel.ios.count > 0 {
                let shareView = HWerweiMaFenXiangView()
                shareView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
                shareView.urlStr = detailTopModel.ios
                HWUniversal.getCurrentVc().view.addSubview(shareView)
            } else {
                if self.detailTopModel.system_type == 2 {
//                    let bundlePath = Bundle.main.bundlePath
//                    let coidPath = bundlePath + "/" + "coid"
//                    let fileManager = FileManager.default
//                    var channel = ""
//                    var member_id = ""
//                    if fileManager.fileExists(atPath: coidPath) {
//                        let allPath:[String] = fileManager.subpaths(atPath: coidPath) ?? []
//                        /// 遍历所有的子路径
//                        for subPath in allPath {
//                            if subPath.contains("coid") {
//                                channel = String((subPath as String).dropFirst(5))
//                            }
//                        }
//                    }
//                    if channel == "" {
//                        member_id = "0"
//                    } else {
//                        member_id = channel
//                    }
                    
                    let urlString = HWGlobalConst.shared.baseUrl + "?ct=h5login&gid=" + self.gameId + "member_id=" + HWLocallyStoredData.getCode()
                    let shareView = HWerweiMaFenXiangView()
                    shareView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
                    shareView.urlStr = urlString
                    HWUniversal.getCurrentVc().view.addSubview(shareView)
                } else {
                    MBProgressHUD.showError("此游戏未上架")
                }
            }
        } else {
            let loginController = HWLoginController()
            self.navigationController?.pushViewController(loginController, animated: true)
        }
    }
}
extension HWGameDetailController:HWFenXiangGameViewDelegate {
    func xuazhongTag(_ tap: Int32) {
        if tap == 0 || tap == 1 {
            /// 微信
            let manager = SDWebImageManager.shared
            manager.loadImage(with: URL(string: detailTopModel.icon), options: .retryFailed) { receivedSize, expectedSize, targetURL in
            } completed: { image, data, error, cacheType, finished, imageURL in
                if finished == true {
                    let urlString = self.detailTopModel.fenxiang + "&member_id=" + HWLocallyStoredData.getCode()
                    let sendReq = SendMessageToWXReq()
                    //不使用文本信息
                    sendReq.bText = false
                    // 0发送到聊天界面  1发送到朋友圈  2发送到微信收藏
                    sendReq.scene = tap
                    //创建分享内容对象
                    let urlMessage = WXMediaMessage.init()
                    //分享标题 urlMessage.description = @"";
                    urlMessage.title = self.detailTopModel.name
                    urlMessage.description = self.detailTopModel.name + self.detailTopModel.type
                    //分享描述
                    urlMessage.setThumbImage(image ?? UIImage())
                    //分享图片,使用SDK的setThumbImage方法可压缩图片大小
                    //创建多媒体对象
                    let webObj = WXWebpageObject.init()
                    //WXWebpageObject *webObj = [WXWebpageObject object];
                    //分享链接
                    webObj.webpageUrl = urlString
                    //完成发送对象实例
                    urlMessage.mediaObject = webObj
                    sendReq.message = urlMessage;
                    //发送分享信息
                    WXApi.send(sendReq)
                }
            }
        }else if tap == 2 {
            //QQ
            let urlString = self.detailTopModel.fenxiang + "&member_id=" + HWLocallyStoredData.getCode()
            let newsObj = QQApiNewsObject.object(with: URL(string: urlString), title: self.detailTopModel.name, description: self.detailTopModel.name + self.detailTopModel.type, previewImageURL: URL(string: self.detailTopModel.icon))
            let req = SendMessageToQQReq(content: (newsObj as! QQApiObject))
            QQApiInterface.send(req)
        }else if tap == 3 {
            //QQ空间
            let urlString = self.detailTopModel.fenxiang + "&member_id=" + HWLocallyStoredData.getCode()
            let newsObj = QQApiNewsObject.object(with: URL(string: urlString), title: self.detailTopModel.name, description: self.detailTopModel.name + self.detailTopModel.type, previewImageURL: URL(string: self.detailTopModel.icon))
            let req = SendMessageToQQReq(content: (newsObj as! QQApiObject))
            QQApiInterface.sendReq(toQZone: req)
        }

    }
}
extension JXPagingListContainerView: JXSegmentedViewListContainer {}
extension HWGameDetailController:JXPagingViewDelegate {
    func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate {
        if self.tagModels[index].type == "0" {
            detailVc.gameId = self.gameId
            detailVc.allButtonClick = {
                self.segmentedView.selectItemAt(index: 1)
            }
            return detailVc
        } else if self.tagModels[index].type == "1" {
            comment.gameId = self.gameId
            return comment
        } else if self.tagModels[index].type == "2" {
            let openService = HWGameDetailOpenServiceController()
            openService.gameId = self.gameId
            return openService
        } else if self.tagModels[index].type == "3" {
            let openService = HWGameDetailOpenServiceController()
            openService.gameId = self.gameId
            return openService
        } else if self.tagModels[index].type == "4" {
            let trade = HWGameDetailTradeController()
            trade.gameId = self.gameId
            return trade
        } else {
            let trade = HWGameDetailTradeController()
            trade.gameId = self.gameId
            return trade
        }
//        if index == 0 {
//
//            detailVc.gameId = self.gameId
//            detailVc.allButtonClick = {
//                self.segmentedView.selectItemAt(index: 1)
//            }
//            return detailVc
//        } else if index == 1 {
//            comment.gameId = self.gameId
//            return comment
//        } else if index == 2 {
//            let openService = HWGameDetailOpenServiceController()
//            openService.gameId = self.gameId
//            return openService
//        } else {
//            let trade = HWGameDetailTradeController()
//            trade.gameId = self.gameId
//            return trade
//        }
    }
    
    func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int {
        if self.detailTopModel.groupInfoModel.name.count > 0 {
            return Int(314*widthScale)
        }else{
            return Int(245*widthScale)
        }
    }
    
    func tableHeaderView(in pagingView: JXPagingView) -> UIView {
        return topView
    }
    
    func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int {
        return Int(41*widthScale)
    }
    
    func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView {
        return segmentBgView
    }
    
    func numberOfLists(in pagingView: JXPagingView) -> Int {
        return segmentedDataSource.dataSource.count
    }
    
}
extension HWGameDetailController:JXSegmentedViewDelegate {
    
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        if self.tagModels[index].type == "4" {
            let community = HWGameCommunityController()
            self.navigationController?.pushViewController(community, animated: true)
            segmentedView.selectItemAt(index: 0)
        }
//        if index == 4 {
//            self.navigationController?.pushViewController(HWGameCommunityController(), animated: true)
//            segmentedView.selectItemAt(index: 0)
//        }
    }
}
